class Slider {
  constructor(id) {
    //id 轮播区域id
    this.sliderBox = document.getElementById(id); //轮播区域

    this.sliderUl = this.sliderBox.children[0]; //轮播区块所在的ul
    this.sliderList = this.sliderUl.children;
    this.i = 0; //控制轮播区块显示的属性
    this.timer = null;
    //每一个轮播图实例都要自动轮播
    this.autoPlay();
    this.clearSet();
  }
  move() {
    this.i++;
    //临界值的控制
    if (this.i == this.sliderList.length) {
      this.i = 0;
    }
    if (this.i == -1) {
      this.i = this.sliderList.length - 1;
    }
    //小圆点
    if (this.circles) {
      //有小圆点 才执行
      for (let i = 0; i < this.sliderList.length; i++) {
        this.circles[i].className = ""; //所有的小圆点类名先清掉
      }
      this.circles[this.i].className = "hover"; //当前的小圆点类名hover
    }
    for (let i = 0; i < this.sliderList.length; i++) {
      this.sliderList[i].style.opacity = 0; //所有区块透明度先变成0
    }
    this.sliderList[this.i].style.opacity = 1; //当前区块透明变成1
  }
  autoPlay() {
    //自动轮播
    this.timer = setInterval(() => {
      //用箭头函数的目的，让this指向实例
      this.move();
    }, 2000);
  }
  addBtn() {
    //左右按钮
    this.oDiv = document.createElement("div");
    this.oDiv.className = "btns";
    this.sliderBox.appendChild(this.oDiv);
    this.oDiv.innerHTML = "<span>&lt;</span><span>&gt;</span>";
    this.aBtns = this.oDiv.children;
    this.aBtns[0].onclick = () => {
      this.i -= 2;
      this.move();
    };
    this.aBtns[1].onclick = () => {
      this.move();
    };
  }
  addCircle() {
    //添加小圆点
    this.oUl = document.createElement("ul");
    this.oUl.className = "circle";
    this.sliderBox.appendChild(this.oUl);
    let str = "";
    for (let i = 0; i < this.sliderList.length; i++) {
      str += `<li></li>`;
    }
    this.oUl.innerHTML = str;
    this.circles = this.oUl.children;
    this.circles[0].className = "hover"; //默认第一个小圆点添加类名
    for (let i = 0; i < this.circles.length; i++) {
      this.circles[i].onclick = () => {
        this.i = i - 1;
        this.move();
      };
    }
  }
  clearSet() {
    //清 开 定时器
    this.sliderBox.onmouseover = () => {
      clearInterval(this.timer);
    };
    this.sliderBox.onmouseout = () => {
      this.timer = setInterval(() => {
        this.move();
      }, 2000);
    };
  }
}
